<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { getCustomTitle } from '@/utils/customStorage.js'
import { getNoticeList, getNoticeDetail, handleProxy } from '@/api/data'
import { handleImage } from '@/api/data'

const route = useRoute()
const customTitle = ref('椒江区人才社区地图')

// 生命周期
onMounted(async () => {
  // 获取自定义标题
  customTitle.value = getCustomTitle()
  
  // 检查是否有 id 参数，如果有则直接加载详情
  const noticeId = route.query.id
  if (noticeId) {
    await loadNoticeDetail(noticeId)
  } else {
    // 否则加载公告列表
    await loadNoticeList()
  }
})

const query = ref('')
const inDetail = ref(false)
const currentNotice = ref(null)
const noticeList = ref([])
const page = ref(1)
const pageSize = ref(6)
const total = ref(0)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 加载公告列表
const loadNoticeList = async () => {
  try {
    const res = await (await getNoticeList(page.value, pageSize.value)).data.data
    console.log(res)

    if (res && res.list) {
      noticeList.value = res.list
      total.value = res.total || 0
    }
  } catch (error) {
    console.error('加载公告列表失败:', error)
  }
}

// 直接加载通知详情（用于从首页跳转）
const loadNoticeDetail = async (id) => {
  try {
    const res = await (await getNoticeDetail(id)).data.data
    if (res) {
      currentNotice.value = res
      inDetail.value = true
    }
  } catch (error) {
    console.error('加载公告详情失败:', error)
    // 如果加载失败，回到列表页
    await loadNoticeList()
  }
}

// 查看详情
const handleView = async (item) => {
  try {
    if (item.type === 'link' && item.linkUrl) {
      window.open(item.linkUrl, 'mozillaWindow', 'popup')
      return
    }
    const res = await (await getNoticeDetail(item.id)).data.data
    if (res) {
      currentNotice.value = res
      inDetail.value = true
    }
  } catch (error) {
    console.error('加载公告详情失败:', error)
  }
}

// 上一页
const prevPage = () => {
  if (page.value > 1) {
    page.value--
    loadNoticeList()
  }
}

// 下一页
const nextPage = () => {
  if (page.value < totalPages.value) {
    page.value++
    loadNoticeList()
  }
}

// 返回列表
const backToList = () => {
  inDetail.value = false
  currentNotice.value = null
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return { day: '--', yearMonth: '--' }
  const date = new Date(dateString)
  const day = date.getDate()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  return {
    day: String(day).padStart(2, '0'),
    yearMonth: `${year}.${month}`,
  }
}

// 过滤后的公告列表
const filteredNoticeList = computed(() => {
  if (!query.value) return noticeList.value
  return noticeList.value.filter((item) => item.title && item.title.includes(query.value))
})
</script>
<template>
  <div class="notice">
    <div class="page-header">
      <div class="return" @click="$router.push('/index')">
        <img class="home" src="/images/icon/home.svg" alt="" />
        回到首页
      </div>
      <div class="title">{{ customTitle }}</div>
    </div>
    <div class="page-body">
      <div class="left">
        <div class="search">
          <div class="search-input" @click="gotoSearch">
            <img class="icon" src="/images/icon/search.svg" alt="" />
            <input class="input" type="text" placeholder="搜索通知公告名称" v-model="query" />
            <img
              v-if="query"
              @click="query = ''"
              class="cancel"
              src="/images/icon/cancel.svg"
              alt=""
            />
          </div>
        </div>
        <img class="banner" src="/images/notice/banner.png" alt="" />
      </div>
      <div class="right">
        <div class="button-group" v-if="!inDetail">
          <div
            class="pre-page"
            @click="prevPage"
            :style="{ opacity: page <= 1 ? 0.5 : 1, cursor: page <= 1 ? 'not-allowed' : 'pointer' }"
          >
            上一页
          </div>
          <div class="page-info">{{ page }} / {{ totalPages }}</div>
          <div
            class="next-page"
            @click="nextPage"
            :style="{
              opacity: page >= totalPages ? 0.5 : 1,
              cursor: page >= totalPages ? 'not-allowed' : 'pointer',
            }"
          >
            下一页
          </div>
        </div>
        <div class="button-group" v-else>
          <div class="pre-page" @click="backToList">返回列表</div>
        </div>
        <div class="header">
          <img class="icon" src="/images/icon/notice.png" alt="" />
          <div class="title">通知公告</div>
        </div>
        <div class="right-body" v-if="!inDetail">
          <div class="item" v-for="item in filteredNoticeList" :key="item.id">
            <div class="date">
              <div class="day">{{ formatDate(item.publishTime).day }}</div>
              <div class="year-month">{{ formatDate(item.publishTime).yearMonth }}</div>
            </div>
            <div class="title">
              {{ item.title }}
            </div>
            <div class="button" @click="handleView(item)">查看详情</div>
          </div>
          <div v-if="!inDetail && filteredNoticeList.length === 0" class="empty-notice">
            暂无通知公告
          </div>
        </div>
        <div v-else class="detail-view">
          <div class="detail-container" v-if="currentNotice">
            <h2 class="detail-title">{{ currentNotice.title }}</h2>
            <div class="detail-info">
              <span class="detail-time"
                >发布时间：{{ formatDate(currentNotice.publishTime).yearMonth }}.{{
                  formatDate(currentNotice.publishTime).day
                }}</span
              >
            </div>
            <div
              class="detail-content"
              v-if="currentNotice.type === 'manual'"
              v-html="handleImage(currentNotice.content)"
            ></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.page-body {
  flex: 1;
  padding: 50px;
  display: flex;
  gap: 25px;
  .left {
    width: 325px;
    .search {
      width: 100%;
      background: #fff;
      border-radius: 20px;
      padding: 12px;
      .search-input {
        width: 100%;
        display: flex;
        align-items: end;
        gap: 10px;
        .icon {
          width: 20px;
          height: 20px;
        }
        .input {
          flex: 1;
          border: none;
          outline: none;
          font-size: 16px;
          &::placeholder {
            color: #999;
          }
        }

        .cancel {
          margin-left: 12px;
          width: 16px;
          height: 16px;
          margin-bottom: 2px;
          margin-right: 5px;
        }
      }
    }
    .banner {
      margin-top: 25px;
      width: 100%;
      height: 577px;
    }
  }
  .right {
    position: relative;
    flex: 1;
    background: #fff;
    border-radius: 20px;
    padding: 38px 13px;
    display: flex;
    flex-direction: column;
    .button-group {
      position: absolute;
      top: 38px;
      right: 13px;
      display: flex;
      gap: 10px;
      z-index: 100;
      .pre-page,
      .next-page {
        cursor: pointer;
        width: 80px;
        height: 40px;
        border-radius: 10px;
        line-height: 40px;
        text-align: center;
        background: linear-gradient(-65deg, #72d7bf 0%, #8fead9 35%, #93e2e6 80%, #7adbe1 100%);
        color: #fff;
        font-size: 14px;
      }
      .page-info {
        width: 80px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: #6c6c6c;
        font-size: 14px;
      }
    }
    .header {
      position: relative;
      margin-bottom: 30px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 18px;
      .icon {
        width: 41px;
        height: 37px;
      }
      .title {
        font-size: 28px;
        color: #6c6c6c;
      }
      &::after {
        content: '';
        position: absolute;
        bottom: -10px;
        left: 50%;
        top: 50%;
        transform: translate(100%, -50%);
        width: 200px;
        height: 2px;
        background: linear-gradient(-90deg, #d4e2e2 0%, #e0eaea 100%);
      }
      &::before {
        content: '';
        position: absolute;
        bottom: -10px;
        left: 20%;
        top: 50%;
        transform: translate(0%, -50%);
        width: 200px;
        height: 2px;
        background: linear-gradient(90deg, #d4e2e2 0%, #e0eaea 100%);
      }
    }
    .right-body {
      height: 100%;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-template-rows: repeat(3, 1fr);
      gap: 25px;
      .item {
        height: 245px;
        position: relative;
        width: 100%;
        border-radius: 0 22px 0 22px;
        background: #fff;
        border: 1px solid #e5e5e5;
        padding: 80px 50px;
        display: flex;
        align-items: center;
        .date {
          display: flex;
          flex-direction: column;
          align-items: center;
          color: #7fdce2;
          border-right: 2px solid #fff;
          padding-right: 25px;
          .day {
            font-size: 79px;
          }
          .year-month {
            font-size: 23px;
          }
        }
        .title {
          margin-left: 25px;
          color: #909090;
          font-size: 22px;
          height: 55px;
        }
        .button {
          cursor: pointer;
          position: absolute;
          bottom: 20px;
          right: 45px;
          background: #fff;
          color: #5ec0c6;
          border: 1.5px solid #5ec0c6;
          width: 147px;
          height: 42px;
          border-radius: 21px;
          line-height: 42px;
          text-align: center;
          font-weight: bold;
        }
        &:hover {
          .date {
            color: #fff;
            text-shadow: 0 4px 12px rgba(85, 170, 176, 0.42);
          }
          .title {
            color: #fff;
            text-shadow: 0 4px 12px rgba(85, 170, 176, 0.42);
          }
          border: none;
          background: linear-gradient(-65deg, #72d7bf 0%, #8fead9 35%, #93e2e6 80%, #7adbe1 100%);
        }
      }
      .empty-notice {
        grid-column: 1 / -1;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 400px;
        font-size: 18px;
        color: #999;
      }
    }
    .detail-view {
      grid-column: 1 / -1;
      padding: 20px;
      overflow-y: auto;
      max-height: 800px;
      .detail-container {
        .detail-title {
          font-size: 32px;
          color: #333;
          margin-bottom: 20px;
          text-align: center;
        }
        .detail-info {
          text-align: center;
          color: #999;
          font-size: 14px;
          margin-bottom: 30px;
          padding-bottom: 20px;
          border-bottom: 1px solid #e5e5e5;
        }
        .detail-content {
          color: #666;
          font-size: 16px;
          line-height: 1.8;
          padding: 0 20px;
          :deep(img) {
            width: 100% !important;
            height: auto !important;
          }
          :deep(p) {
            margin-bottom: 15px;
          }
        }
      }
    }
  }
}
.notice {
  display: flex;
  flex-direction: column;
  background: url('/images/home/bg.png') no-repeat center top;
  background-repeat: no-repeat;
  background-size: cover;
  width: 1920px;
  height: 100vh;
  overflow: hidden;
  position: relative;
}
</style>
